import "reflect-metadata";
import { Request, Response } from "express";
import { get, post } from "../decorator/request";
import { controller } from "../decorator/controller";
import { getResponseData } from "../utils/util";

@controller
class LoginController {
  @post("/login")
  login(req: Request, res: Response): void {
    const { password } = req.body;
    const isLogin = !!(req.session ? req.session.login : false);
    if (isLogin) {
      res.json(getResponseData(false, "Already login!"));
    } else {
      if (password === "123" && req.session) {
        req.session.login = true;
        res.json(getResponseData(true));
      } else {
        res.json(getResponseData(false, "Login failed!"));
      }
    }
  }

  @get("/logout")
  logout(req: Request, res: Response): void {
    if (req.session) {
      req.session.login = undefined;
    }
    res.json(getResponseData(true));
  }

  @get("/")
  home(req: Request, res: Response): void {
    const isLogin = !!(req.session ? req.session.login : false);
    if (isLogin) {
      res.send(`
          <html>
            <body>
              <a href='/showdata'>Show</a>
              <a href='/getdata'>Get</a>
              <a href='/logout'>Exit</a>
            </body>
          </html>
          `);
    } else {
      res.send(`
          <html>
            <body>
              <form method="post" action="/login">
                <input type="password" name="password"/>          
                <button>summit</button>
              </form>
            </body>
          </html>
          `);
    }
  }
}
